package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"math"
	"register/models"
)

type RegisterController struct {
	beego.Controller
}

func (c *RegisterController) Add() {
	number := c.GetString("number")
	name := c.GetString("name")
	tel := c.GetString("tel")
	uid := c.GetString("uid")
	address := c.GetString("address")

	if number == "" || name == "" || tel == "" || uid == "" || address == "" {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"mag":  "挂号信息不能为空",
		}
		c.ServeJSON()
		return
	}

	var register models.Register
	register.Number = number
	register.Name = name
	register.Tel = tel
	register.Uid = uid
	register.Address = address

	err := register.Creates()
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"mag":  "挂号失败",
		}
		c.ServeJSON()
		return
	}
	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"mag":  "挂号成功",
	}
	c.ServeJSON()
}

func (c *RegisterController) List() {
	page, _ := c.GetInt("page", 1)
	pageSize, _ := c.GetInt("page_size", 5)

	var count int64
	models.DB.Model(&models.Register{}).Count(&count)
	sum := int(math.Ceil(float64(count) / float64(pageSize)))
	up := page - 1
	if up < 1 {
		up = 1
	}
	down := page + 1
	if down > sum {
		down = sum
	}

	var registered models.Register
	register, err := registered.List(page, pageSize)
	if err != nil {
		c.Data["json"] = map[string]interface{}{
			"code": 0,
			"mag":  "查询失败",
		}
		c.ServeJSON()
		return
	}

	pageData := map[string]interface{}{
		"sum":  sum,
		"up":   up,
		"down": down,
		"data": register,
	}

	c.Data["json"] = map[string]interface{}{
		"code": 200,
		"mag":  "查询成功",
		"data": pageData,
	}
	c.ServeJSON()
}
